package com.battle.service.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.entity.*;
import com.battle.pojo.param.trainingAchievement.EditTrainingAchievementParam;
import com.battle.pojo.param.trainingAchievement.GetTrainingAssessmentListByUserIdParam;
import com.battle.pojo.param.trainingAchievement.ImportTrainingAssessmentParam;
import com.battle.pojo.param.trainingAssessment.*;
import com.battle.pojo.vo.carWarCase.GetCarWarCaseListVo;
import com.battle.pojo.vo.trainingAssessment.*;
import com.battle.pojo.dto.trainingAssessment.*;
import com.battle.service.repository.in.OrganizationRepository;
import com.battle.service.repository.in.PersonOrganizationMpRepository;
import com.battle.service.repository.in.PersonWarCaseRepository;
import com.battle.service.repository.in.TrainingAssessmentRepository;
import com.battle.service.service.in.TrainingAssessmentService;
import com.battle.service.utils.ExcelUtils;
import jakarta.servlet.http.HttpServletResponse;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：训练考核服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class TrainingAssessmentServiceImpl implements TrainingAssessmentService {

    private final TrainingAssessmentRepository trainingAssessmentRepository;
    private final PersonWarCaseRepository personWarCaseRepository;
    private final PersonOrganizationMpRepository personOrganizationMpRepository;
    private final OrganizationRepository organizationRepository;

    public TrainingAssessmentServiceImpl(TrainingAssessmentRepository trainingAssessmentRepository, PersonWarCaseRepository personWarCaseRepository, PersonOrganizationMpRepository personOrganizationMpRepository, OrganizationRepository organizationRepository) {
        this.trainingAssessmentRepository = trainingAssessmentRepository;
        this.personWarCaseRepository = personWarCaseRepository;
        this.personOrganizationMpRepository = personOrganizationMpRepository;
        this.organizationRepository = organizationRepository;
    }


    /**
     * 创建训练考核
     *
     * @param param
     */
    @Override
    public void createTrainingAssessment(CreateTrainingAssessmentParam param) {
        TrainingAssessment trainingAssessment = new TrainingAssessment();
        BeanUtils.copyProperties(param, trainingAssessment);
        Long id = IdGenerator.SNOW.generate();
        trainingAssessment.setId(id);
        trainingAssessmentRepository.create(trainingAssessment);
    }



    /**
     * 移除训练考核
     *
     * @param id
     */
    @Override
    public void removeTrainingAssessment(Long id) {
        trainingAssessmentRepository.removeById(id);
    }

    /**
     * 启动/禁用训练考核
     *
     * @param id
     */
    @Override
    public void enabledTrainingAssessment(Long id) {
        TrainingAssessment trainingAssessment = trainingAssessmentRepository.getByIdCheck(id);
        trainingAssessment.setIsDisable(!trainingAssessment.getIsDisable());
        trainingAssessmentRepository.edit(trainingAssessment);
    }

    /**
     * 获取训练考核详情
     *
     * @param id
     * @return
     */
    @Override
    public GetTrainingAssessmentVo getTrainingAssessment(Long id) {
        TrainingAssessment trainingAssessment = trainingAssessmentRepository.getByIdCheck(id);
        GetTrainingAssessmentVo vo = new GetTrainingAssessmentVo();
        BeanUtils.copyProperties(trainingAssessment, vo);
        return vo;
    }

    /**
     * 获取训练考核 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetTrainingAssessmentListVo> getTrainingAssessmentList(GetTrainingAssessmentListParam param) {

        SelectTrainingAssessmentDto dto = new SelectTrainingAssessmentDto();
        BeanUtils.copyProperties(param, dto);
        Page<TrainingAssessment> page = trainingAssessmentRepository.selectTrainingAssessment(dto);
        List<TrainingAssessment> trainingAssessmentList = page.getRecords();
        List<GetTrainingAssessmentListVo> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(trainingAssessmentList)) {
            List<Long> userIds = new ArrayList<>();

            trainingAssessmentList.forEach(v -> {
                userIds.add(v.getPersonId());
            });

            Map<Long, PersonWarCase> userMap = personWarCaseRepository.getMap(userIds);
            for (TrainingAssessment trainingAssessment : trainingAssessmentList) {
                GetTrainingAssessmentListVo vo = new GetTrainingAssessmentListVo();
                BeanUtils.copyProperties(trainingAssessment, vo);
                PersonWarCase operation = userMap.get(trainingAssessment.getPersonId());
                if (operation != null) {
                    vo.setPersonName(operation.getName());
                    //多组织架构
                    List<PersonOrganizationMp> personOrganizationMps = personOrganizationMpRepository.selectByOrganizationId(null, operation.getId());
                    if (CollectionUtil.isNotEmpty(personOrganizationMps)) {
                        List<Long> organizationIds = new ArrayList<>();
                        personOrganizationMps.forEach(personOrganizationMp -> {
                            organizationIds.add(personOrganizationMp.getOrganizationId());
                        });
                        List<Organization> organizations = organizationRepository.listByIds(organizationIds);
                        if (CollectionUtil.isNotEmpty(organizations)) {
                            String organizationNames = organizations.stream().map(Organization::getName).collect(Collectors.joining(","));
                            vo.setOrganizationName(organizationNames);
                        }
                    }
                }
                list.add(vo);
            }

        }
        return new PageResult<>(list, page);
    }

    /**
     * 个人培训考核列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetTrainingAssessmentListVo> getTrainingAssessmentListByUserId(GetTrainingAssessmentListByUserIdParam param) {
        SelectTrainingAssessmentDto dto = new SelectTrainingAssessmentDto();
        BeanUtils.copyProperties(param, dto);
        Page<TrainingAssessment> page = trainingAssessmentRepository.selectTrainingAssessment(dto);
        List<TrainingAssessment> trainingAssessmentList = page.getRecords();
        List<GetTrainingAssessmentListVo> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(trainingAssessmentList)) {
            List<Long> userIds = new ArrayList<>();

            trainingAssessmentList.forEach(v -> {
                userIds.add(v.getPersonId());
            });

            Map<Long, PersonWarCase> userMap = personWarCaseRepository.getMap(userIds);
            for (TrainingAssessment trainingAssessment : trainingAssessmentList) {
                GetTrainingAssessmentListVo vo = new GetTrainingAssessmentListVo();
                BeanUtils.copyProperties(trainingAssessment, vo);
                PersonWarCase operation = userMap.get(trainingAssessment.getPersonId());
                if (operation != null) {
                    vo.setPersonName(operation.getName());
                    //多组织架构
                    List<PersonOrganizationMp> personOrganizationMps = personOrganizationMpRepository.selectByOrganizationId(null, operation.getId());
                    if (CollectionUtil.isNotEmpty(personOrganizationMps)) {
                        List<Long> organizationIds = new ArrayList<>();
                        personOrganizationMps.forEach(personOrganizationMp -> {
                            organizationIds.add(personOrganizationMp.getOrganizationId());
                        });
                        List<Organization> organizations = organizationRepository.listByIds(organizationIds);
                        if (CollectionUtil.isNotEmpty(organizations)) {
                            String organizationNames = organizations.stream().map(Organization::getName).collect(Collectors.joining(","));
                            vo.setOrganizationName(organizationNames);
                        }
                    }
                }
                list.add(vo);
            }

        }
        return new PageResult<>(list, page);
    }

    /**
     * 导出个人培训考核
     * @param param
     * @param response
     * @throws IOException
     */
    @Override
    public void export(GetTrainingAssessmentListByUserIdParam param, HttpServletResponse response) throws IOException {
        param.setSize(Long.MAX_VALUE);
        PageResult<GetTrainingAssessmentListVo> pageResult = getTrainingAssessmentListByUserId(param);
        List<GetTrainingAssessmentListVo> list = pageResult.getRecords();
        ExcelUtils.exportExcel(list, "个人训练记录", "个人训练记录", GetTrainingAssessmentListVo.class, "个人训练记录",response);
    }

    /**
     * 获取训练考核下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetTrainingAssessmentDownListVo> getTrainingAssessmentDownList(GetTrainingAssessmentDownListParam param) {
        TrainingAssessment po = new TrainingAssessment();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<TrainingAssessment> trainingAssessmentList = trainingAssessmentRepository.getListByEntity(po);

        List<GetTrainingAssessmentDownListVo> list = new ArrayList<>();
        for (TrainingAssessment trainingAssessment : trainingAssessmentList) {
            GetTrainingAssessmentDownListVo vo = new GetTrainingAssessmentDownListVo();
            BeanUtils.copyProperties(trainingAssessment, vo);
            list.add(vo);
        }
        return list;
    }

    /**
     * 导入
     * @param param
     */
    @Override
    public void importTrainingAssessment(ImportTrainingAssessmentParam param) throws IOException {
        StringBuffer error = new StringBuffer();

        InputStream inputStream =null;
        try {
            URL url=new URL(param.getFileUrl());
            URLConnection urlConnection = url.openConnection();
            inputStream=urlConnection.getInputStream();
            if (inputStream == null) {
                throw new BizException("文件不存在");
            }

            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setStartRows(0);

            List<EditTrainingAssessmentParam> result = ExcelImportUtil.importExcel(inputStream, EditTrainingAssessmentParam.class, params);
            for (EditTrainingAssessmentParam excel : result) {
                PersonWarCase personWarCase = new PersonWarCase();
                personWarCase.setName(excel.getPersonName());
                personWarCase.setIsDelete(false);
                personWarCase = personWarCaseRepository.getByEntity(personWarCase);
                if (personWarCase == null) {
                    error.append("人员名称：" + excel.getPersonName() + "不存在\n");
                    continue;
                } else {
                    TrainingAssessment details = new TrainingAssessment();
                    BeanUtils.copyProperties(excel, details);
                    details.setId(IdGenerator.SNOW.generate());
                    details.setPersonId(personWarCase.getId());
                    trainingAssessmentRepository.save(details);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
        }


        if (!StringUtils.isEmpty(error.toString())) {
            throw new BizException(error.toString());
        }

    }


}



